<?php
session_start();

include("language.php");
include('database.php');

if(isset($_SESSION['connected']) AND $_SESSION['connected']) 
{
    if(isset($_POST['rulesAccepted']) AND $_POST['rulesAccepted'])
    {
        $_GET['id'] = htmlspecialchars($_GET['id']);

        $query = $db->prepare("SELECT * FROM draw where id = ?");
        $query->execute(array($_GET['id']));

        $isValid = false;

        if($query->rowCount() == 1)
        {
            $data = $query->fetch();

            if($data['status'] == 1)
            {
                $drawQuery = $db->prepare("SELECT * FROM drawParticipation WHERE user_id = ? AND draw_id = ?");
                $drawQuery->execute(array($_SESSION['id'], $_GET['id']));

                if($drawQuery->rowCount() > 0)
                {
                    echo '<p>' . $doDraw_alreadySubscribed . '</p>';
                }
                else 
                {
                    $newParticipation = $db->prepare("INSERT INTO drawParticipation(draw_id, user_id, status, participationDate) VALUES(?, ?, ?, NOW())");
                    $newParticipation->execute(array($_GET['id'], $_SESSION['id'], 1));
                    header("Location: draws.php");
                }
            }
            else echo '<p>' . $participateToDraw_youCantYetParticipate . '</p>';
        }
        else echo '<p>' . $participateToDraw_invalidDrawing . '</p>';
    }
    else echo '<p>' . $doDraw_didntReadRules . '</p>';
}
?>